//
//  BUAdsManager.swift
//  LeTu
//
//  Created by g1 on 2024/3/3.
//

import Foundation
import BUAdSDK
import AppTrackingTransparency

let kAdsManager = BUAdsManager.shared
class BUAdsManager: NSObject {
    
    static let shared = BUAdsManager()
    
    private var adsAppId = "5488381"
    
    /// 穿山甲是否sdk初始化成功
    private(set) var isInitCSJ = false
    /// 穿山甲数据
    private(set) var adsModel: AdsModel?
    
    /// 初始化穿山甲
    func initBUAds() {
        
//        requestAdsIdList{ _ in }
        
        let configuration = BUAdSDKConfiguration()
        configuration.appID = adsAppId
        configuration.useMediation = true
        configuration.appLogoImage = UIImage(named: "logo_icon")
        configuration.debugLog = NSNumber(integerLiteral: 0)
        BUAdSDKManager.start(asyncCompletionHandler: { [weak self] isSuccess, error in
            self?.isInitCSJ = isSuccess
            if isSuccess {
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: NSNotification.Name("AdsInitSuccessNotification"), object: nil)
                }
            }
        })
        
        /// 申请本地网络权限
        ATTrackingManager.requestTrackingAuthorization(completionHandler: { _ in })

    }
    
    /// 请求广告id列表
    func requestAdsIdList(completeHandle: @escaping NetworkRequestHandle) {
        
        var params = [String: Any]()
        // 用户类型（1:自用， 2：合作方用）, 目前固定传参：1
        params["ownerType"] = 1
        // 平台（1：Android 2：iOS）
        params["platform"] = 2
        apiProvider.request(api: .getAds(params: params)) { [weak self] json, jsonArr, code in
            MYLog("获取广告位列表：", json, code)
            
            var dialog = DialogMessage()
            guard let strongSelf = self, let pm = Mapper<ResponseModel>().map(JSON: json), code == 200 else { return completeHandle(dialog) }
            dialog.code = pm.code
            dialog.message = pm.msg
            guard pm.code == 200, let data = pm.data as? [String: Any], let model = Mapper<AdsModel>().map(JSON: data) else {
                return completeHandle(dialog)
            }
            dialog.data = model
            strongSelf.adsModel = model
            completeHandle(dialog)
        } failureHandler: { _ in
            completeHandle(DialogMessage())
        }

    }
    
}

// MARK: - 开屏广告
extension BUAdsManager {
        
    /// 加载开屏广告
    func loadOpeningTheAdvertising(delegate: BUSplashAdDelegate) -> BUSplashAd? {
        
//        guard let adsModel = kAdsManager.adsModel else { return nil }
        let slot = BUAdSlot()
        slot.id = "102691105"
        let splashAd = BUSplashAd(slot: slot, adSize: CGSize(width: screenWidth, height: screenHeight))
        splashAd.delegate = delegate
        //splashAd.hideSkipButton = true
        return splashAd
        
    }

}

// MARK: ----- 激励广告
extension BUAdsManager {
    
    // 加载激励广告
    func loadRewardedTheAdvertising(delegate: BUNativeExpressRewardedVideoAdDelegate) -> BUNativeExpressRewardedVideoAd? {

        guard let adsModel = kAdsManager.adsModel else { return nil }
        let slot = BUAdSlot()
        slot.id = adsModel.rewardAdsId
        slot.mediation.mutedIfCan = true;    // 奖励发放设置
        let rewardedVideoModel = BURewardedVideoModel()
        let rewardedVideoAd = BUNativeExpressRewardedVideoAd(slot: slot, rewardedVideoModel: rewardedVideoModel)
        rewardedVideoAd.delegate = delegate
        // 如果使用再看一次功能时，需要设置rewardPlayAgainInteractionDelegate，如果要区分是否为再看一次请使用不同的代理对象
        // rewardedVideoAd.rewardPlayAgainInteractionDelegate = self
        // 设置竖屏
        rewardedVideoAd.mediation?.addParam(NSNumber(value: 0), withKey: "show_direction")
        return rewardedVideoAd
        
    }

}

// MARK: - 模版渲染信息流广告
extension BUAdsManager {
    
    /// 模版渲染信息流广告
    func loadNativeExpressTheAdvertising(adSize: CGSize, vc: UIViewController, delegate: BUNativeAdsManagerDelegate) -> BUNativeAdsManager? {
        
        guard let adsModel = kAdsManager.adsModel else { return nil }

        let slot = BUAdSlot()
        slot.id = adsModel.feedAdsId
        slot.adSize = adSize
        slot.mediation.mutedIfCan = true
        let adManager = BUNativeAdsManager(slot: slot)
        adManager.mediation?.rootViewController = vc
        adManager.delegate = delegate
        
        return adManager
        
    }
    
    /// 销毁上次信息流广告对象
    func destoryNativeExpressAdManager(_ manager: BUNativeAdsManager) {
        manager.mediation?.destory()
    }
    
}

// MARK: - 广告位id信息
class AdsModel: Mappable {

    var createTime = ""
    /// 信息流广告位Id
    var feedAdsId = "102689162"
    var id = 2
    var name = ""
    /// 用户类型（1：白用，2：合作）
    var ownerType = 1
    /// 平台(1: Android 2: i0S)
    var platform = 2
    var remarks = ""
    /// 激励视频广告位Id
    var rewardAdsId = "102691006"
    /// 开屏广告位Id
    var splashAdsId = "102691105"
    var status = 0
    var updateTime = ""
    
    init() {
        
    }
    
    required init?(map: ObjectMapper.Map) {
        
    }
    
    func mapping(map: ObjectMapper.Map) {
        
        createTime <- map["createTime"]
        feedAdsId <- map["feedAdsId"]
        id <- map["id"]
        name <- map["name"]
        ownerType <- map["ownerType"]
        platform <- map["platform"]
        remarks <- map["remarks"]
        rewardAdsId <- map["rewardAdsId"]
        splashAdsId <- map["splashAdsId"]
        status <- map["status"]
        updateTime <- map["updateTime"]
        
    }
    
}


